<?php

namespace app\common\model\points_mall;

use think\Model;

class Category extends Model
{
    // 数据库
    protected $name = 'points_mall_category';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'status_text',
        'create_date'

    ];

    public function getStatusTextAttr($value, $data)
    {
        return $data['status'] == 'normal' ? '启用' : '禁用';
    }

    public function getCreateDateAttr($value, $data)
    {
        if (isset($data['createtime']) && $data['createtime']) {
            return date('Y-m-d H:i', $data['createtime']);
        } else {
            return '';
        }
    }


    public function getList($where = [], $page = 1, $limit = 10)
    {
        $total = $this->where($where)->count();
        $list = $this->where($where)
            ->page($page, $limit)
            ->order('weigh desc, id desc')
            ->select();

        return ['total' => $total, 'data' => $list];
    }

    public function add($data)
    {
        // 处理参数JSON
        if (isset($data['params']) && is_array($data['params'])) {
            $data['params'] = json_encode($data['params'], JSON_UNESCAPED_UNICODE);
        }

        return $this->allowField(true)->save($data);
    }


    public function edit($data)
    {
        // 处理参数JSON
        if (isset($data['params']) && is_array($data['params'])) {
            $data['params'] = json_encode($data['params'], JSON_UNESCAPED_UNICODE);
        }

        return $this->allowField(true)->save($data, ['id' => $data['id']]);
    }

    public function remove($id)
    {
        return $this->where('id', $id)->delete();
    }

    public function updateStatus($id, $status)
    {
        return $this->where('id', $id)->update(['status' => $status]);
    }

}
